import { inject, h, type Slots } from 'vue'
import type { UseLinkOptions } from 'vue-router'
import type { Router, RouteLocationNormalized } from './types'

function useLink(props: UseLinkOptions) {
  // 拿到 router 对象
  const router: Router = inject('router') as Router
  // 创建导航方法
  function navigate() {
    router.push(props.to as RouteLocationNormalized)
  }

  return {
    navigate
  }
}

export const RouterLink = {
  name: 'RouterLink',
  props: {
    to: {
      type: [String, Object],
      required: true
    }
  },
  setup(props: UseLinkOptions, { slots }: { slots: Slots }) {
    const link = useLink(props)
    return () => {
      return h(
        'a',
        {
          onClick: link.navigate,
          style: {
            cursor: 'pointer'
          }
        },
        slots.default && slots.default()
      )
    }
  }
}

